package com.ita.shoppingcart.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes.Name;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ita.shoppingcart.bean.Goods;
import com.ita.shoppingcart.bean.User;
import com.ita.shoppingcart.cart.UserManager;
import com.ita.shoppingcart.cart.UserManagerImpl;
import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * Servlet implementation class UserLoginServlet
 */
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserManager userManager = new UserManagerImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uname = request.getParameter("uname");
		String pwd = request.getParameter("pwd");
		System.out.println(uname + "-------------" + pwd);
		User user = userManager.login(uname, pwd);
		if(user != null){
			//TODO redirect to goods list
			System.out.println("user login success!");
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
//			request.getRequestDispatcher("./listGoods").forward(request, response);
			response.sendRedirect("./listGoods");
			Map<Integer, Goods> cart = new HashMap<Integer, Goods>();
			session.setAttribute("Cart", cart);
		}else {
			//TODO redirect to login page;
			System.out.println("user login faild!");
			request.setAttribute("faildMsg", "Login failed! Pls check your user name and password again!");
			request.getRequestDispatcher("./jsp/index.jsp").forward(request, response);
		}
	}

}
